
import React, {Fragment} from "react";
import {Table, Popconfirm, Form, Card, Button, message, Divider} from 'antd';
import FormInput from "../../../components/form/FormInput";
import {observer} from "mobx-react";
import {simpleCreateOrUpdate, simpleDelete, simpleIndex} from "../../../api/work/GenerateApi";
import FormMulInput from "../../../components/form/FormMulInput";
import FormTimePicker from "../../../components/form/FormTimePicker";
import FormDatePicker from "../../../components/form/FormDatePicker";
import FormMonthPicker from "../../../components/form/FormMonthPicker";
import FormYearPicker from "../../../components/form/FormYearPicker";
import FormPointPicker from "../../../components/form/FormPointPicker";

const EditableContext = React.createContext();

/**
 * 简单(列表)录入页面
 */
class EditableCell extends React.Component {
    constructor(props) {
        super(props);
        this.state={}
    }
    renderCell = (form) => {
        const {
            editing,
            dataIndex,
            title,
            inputType,
            record,
            index,
            children,
            ...restProps
        } = this.props;
        return (
            <td {...restProps}>
                {editing ? (
                    <Fragment>
                        {inputType === "FormInput" && <FormInput form={form} label={title} field={dataIndex} allowClear={true} placeholder={title} initialValue={record[dataIndex]} rules={[]}/>}
                        {inputType === "FormMulInput" && <FormMulInput form={form} label={title} field={dataIndex}  placeholder={title} rows={4} allowClear={true} initialValue={record[dataIndex]} rules={[]}/>}
                        {inputType === "FormTimePicker" && <FormTimePicker form={form} label={title} field={dataIndex} placeholder={title} initialValue={record[dataIndex]} rules={[]}/>}
                        {inputType === "FormDatePicker" && <FormDatePicker form={form} label={title} field={dataIndex} placeholder={title} initialValue={record[dataIndex]} rules={[]}/>}
                        {inputType === "FormMonthPicker" &&<FormMonthPicker form={form} label={title} field={dataIndex} placeholder={title} initialValue={record[dataIndex]} rules={[]}/>}
                        {inputType === "FormYearPicker" && <FormYearPicker form={form} label={title} field={dataIndex} disabled={title} placeholder={title} initialValue={record[dataIndex]} rules={[]} />}
                        {inputType === "FormPointPicker" && <FormPointPicker form={form} placeholder={title} field={dataIndex} initialValue={record[dataIndex]} rules={[]} />}
                    </Fragment>
                ) : (
                    children
                )}
            </td>
        );
    };

    render() {
        return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
    }
}

@observer
class Index extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            data:[],
            columns:[],
            editingKey: '' ,
            fetching:false,
            uri:"",
        };
    }

    getUri = (nextProps = null) => {
        let uri = nextProps ? nextProps.match.params.uri : this.props.match.params.uri;
        if (uri){
            return uri.replace(/\./g,"\/");
        }else {
            message.error("uri缺失")
            return false;
        }
    };

    //解决参数改变组件不更新的问题
    componentWillReceiveProps = (nextProps) => {
        let that = this;
        let new_uri = this.getUri(nextProps);
        if (this.state.uri !== new_uri){
           this.setState({
               uri:new_uri
           },function () {
               that.fetchRecords()
           })
        }

    };

    componentDidMount() {
        let uri = this.getUri();
        if (uri){
            this.setState({
                uri:uri
            },function () {
                this.fetchRecords()
            })
        }

    }


    fetchRecords = () => {
        this.setState({fetching:true});
        simpleIndex({page:this.state.uri}).then(response => {
            if (response.data.code === 200){
                let columns = response.data.column;
                columns.push({
                    title: '操作',
                    dataIndex: 'operation',
                    render: (text, record) => {
                        const { editingKey } = this.state;
                        const editable = this.isEditing(record);
                        return (
                            <span>
                                {
                                    editable ? (
                                        <span>
              <EditableContext.Consumer>
                {form => (
                    <a
                        onClick={() => this.save(form, record.key)}
                        style={{ marginRight: 8 }}
                    >
                        保存
                    </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="确定要取消操作吗?" onConfirm={() => this.cancel(record.key)}>
                <a>取消</a>
              </Popconfirm>
            </span>
                                    ) : (
                                       <Fragment>
                                           <a disabled={editingKey !== ''} onClick={() => this.edit(record.key)}>
                                               编辑
                                           </a>
                                           <Divider type="vertical" />
                                           <Popconfirm title="确定要删除改行数据吗?" onConfirm={() => this.deleteRow(record)}>
                                               <a>删除</a>
                                           </Popconfirm>
                                       </Fragment>
                                    )
                                }
                            </span>
                        )
                    },
                });

                this.setState({
                    columns: columns,
                    data: response.data.data,
                    fetching:false
                })
            }
        })
    };

    createOrUpdateRecord = (data) => {
        data["page"] = this.state.uri;
        data["id"] = this.state.editingKey;
        simpleCreateOrUpdate(data).then(response => {
            if (response.data.code === 200){
                message.success(response.data.msg);
                this.fetchRecords()
            }
        })
    };



    isEditing = record => record.key === this.state.editingKey;

    cancel = () => {
        this.setState({ editingKey: '' });
    };

    save(form, key) {
        form.validateFields((error, row) => {
            if (error) {
                return;
            }
            const newData = [...this.state.data];
            const index = newData.findIndex(item => key === item.key);
            if (index > -1) {
                const item = newData[index];
                newData.splice(index, 1, {
                    ...item,
                    ...row,
                });
                this.setState({ data: newData, editingKey: '' });
            } else {
                newData.push(row);
                this.setState({ data: newData, editingKey: '' });
            }

            console.log(this.state.editingKey)
            console.log("新数据",row)
            this.createOrUpdateRecord(row)
        });
    }

    edit(key) {
        this.setState({ editingKey: key });
    }

    addRow = () => {
        let new_obj = {};
        this.state.columns.map(item => {
            if (item.dataIndex !== "operation"){
                new_obj[item.dataIndex] = "";
            }
        });
        this.createOrUpdateRecord(new_obj);
    };

    deleteRow = (record) => {
        simpleDelete({id:record.id,page:this.state.uri}).then(response => {
            if (response.data.code === 200){
                message.success(response.data.msg);
                this.fetchRecords();
            }
        });

    };

    render() {
        const components = {
            body: {
                cell: EditableCell,
            },
        };

        const columns = this.state.columns.map(col => {
            if (!col.editable) {
                return col;
            }
            return {
                ...col,
                onCell: record => ({
                    record,
                    inputType: col.inputType,
                    dataIndex: col.dataIndex,
                    title: col.title,
                    editing: this.isEditing(record),
                }),
            };
        });

        return (
           <Fragment>
               <Card>
                   {this.state.fetching === false && <EditableContext.Provider value={this.props.form}>
                       <Button onClick={this.addRow} icon={"plus"} type="primary" style={{ marginBottom: 16 }}>
                           增加一行
                       </Button>
                       <Table
                           components={components}
                           bordered
                           dataSource={this.state.data}
                           columns={columns}
                           rowClassName="editable-row"
                           pagination={{
                               onChange: this.cancel,
                           }}
                       />
                   </EditableContext.Provider>}
               </Card>
           </Fragment>

        );
    }
}

export default Form.create()(Index);
